package com.fuful.service;

import com.fuful.domain.OrderDetails;
import com.fuful.domain.Orders;
import com.fuful.domain.Product;
import com.fuful.domain.Users;
import com.fuful.tools.DBHelper;
import com.fuful.tools.OrderTools;

import java.util.ArrayList;
import java.util.List;

public class OrderService {

    public boolean createOrder(Orders orders){
        List<String> sqls = new ArrayList<>();
        //插入订单
        String temp = "insert into orders(orderid,uid,orderprice)values('"+ orders.getOrderid() +"',"+ orders.getUid() +","+ orders.getOrderprice() +")";
        System.out.println(temp);
        sqls.add("insert into orders(orderid,uid,orderprice)values('"+ orders.getOrderid() +"',"+ orders.getUid().getUid() +","+ orders.getOrderprice() +")");
        //插入订单明细
        List<OrderDetails> details = orders.getDetails();
        for (OrderDetails d: details) {
            String sql = "insert into orders_details(orderid,pid,pnum)values('"+ d.getOrderid().getOrderid() +"',"+ d.getPid().getPid() +","+ d.getPnum() + ")";
            System.out.println(sql);
            sqls.add(sql);
        }
        //插入交易流水
        sqls.add("insert into jyinfo(jycode,jytype,jymomey)values('"+ OrderTools.createOrderCode() +"','1',"+ orders.getOrderprice() +")");
        int[] flag = DBHelper.executeUpdataBatch(sqls);
        if(flag != null){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        //订单流水
        String orderCode = OrderTools.createOrderCode();
        //生成订单对象
        Orders myOrder = new Orders(
                orderCode,
                new Users(6)
        );
        //生成订单明细
        List<OrderDetails> details = new ArrayList<>();
        OrderDetails orderDetails = new OrderDetails(
                myOrder,
                new Product(1,12.8f),
                3
        );
        details.add(orderDetails);
        OrderDetails orderDetails2 = new OrderDetails(
                myOrder,
                new Product(2,1.0f),
                4
        );
        details.add(orderDetails2);
        OrderDetails orderDetails3 = new OrderDetails(
                myOrder,
                new Product(3,6.5f),
                5
        );
        details.add(orderDetails3);
        OrderDetails orderDetails4 = new OrderDetails(
                myOrder,
                new Product(4,99.0f),
                6
        );
        details.add(orderDetails4);
        float totalPrice = 0.0f;
        for (OrderDetails d: details) {
            totalPrice = totalPrice + d.getPid().getPprice() * d.getPnum();
        }

        myOrder.setDetails(details);
        myOrder.setOrderprice(totalPrice);

        //调用业务逻辑
        OrderService os = new OrderService();
        boolean flag = os.createOrder(myOrder);
        if(flag){
            System.out.println("下订单成功了");
        }else{
            System.out.println("订单失败！");
        }
    }

}
